package com.bw.zonghe0719.fragment

import android.content.Context
import android.os.Bundle
import android.os.Handler
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import androidx.appcompat.widget.MenuPopupWindow
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.ToastUtils
import com.bw.base.entity.Roll
import com.bw.base.mvvm.BaseFragment
import com.bw.zonghe0719.R
import com.bw.zonghe0719.adapter.CouponAdapter
import com.bw.zonghe0719.adapter.GoodsAdapter
import com.bw.zonghe0719.adapter.MenuAdapter
import com.bw.zonghe0719.adapter.NewsAdapter
import com.bw.zonghe0719.adapter.TypeAdapter
import com.bw.zonghe0719.databinding.FragmentHomeBinding
import com.bw.zonghe0719.fragment.home.HomeVieModel
import com.bw.zonghe0719.utils.GlideUtils
import com.scwang.smart.refresh.layout.api.RefreshLayout
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener
import com.youth.banner.BannerConfig
import com.youth.banner.loader.ImageLoader
import java.util.Timer
import java.util.TimerTask

class HomeFragment : BaseFragment<FragmentHomeBinding,HomeVieModel>() {
    var imgs= mutableListOf<String>()
    private lateinit var menuAdapter: MenuAdapter
    private lateinit var newsAdapter: NewsAdapter
    private lateinit var typeAdapter: TypeAdapter
    private lateinit var goodsAdapter: GoodsAdapter
    private lateinit var couponAdapter: CouponAdapter
    lateinit var timer: Timer
    var handler=Handler()
    var index=0//当前显示的新闻的下标
    //商品相关数据
    var type=4//分类 默认为4  因为它在第一个
    var limit=4
    var page=1
    var couponIndex=-1
    override fun initView() {
        //请求数据
        viewModel.index()
        binding.clSearch.setOnClickListener {
            ARouter.getInstance().build("/app/search/SearchActivity").navigation()
        }
        //菜单
        menuAdapter=MenuAdapter()
        binding.rvMenu.layoutManager=GridLayoutManager(requireContext(),5)
        binding.rvMenu.adapter=menuAdapter
        //新闻
        newsAdapter= NewsAdapter()
        binding.rvNews.layoutManager=LinearLayoutManager(requireContext())
        binding.rvNews.adapter=newsAdapter
          //让新闻的数据可以自动纵向滚动  使用定时器
        timer=Timer()
        timer.schedule(object :TimerTask(){
            override fun run() {
                handler.post {
                    binding.rvNews.scrollToPosition(index)//让rv显示指定下标的数据
                    index++//下标自增
                    if(index==newsAdapter.data.size){
                        index=0
                    }
                }
            }

        },0,3000)
        //分类
        typeAdapter=TypeAdapter()
        binding.rvType.layoutManager=GridLayoutManager(requireContext(),4)
        binding.rvType.adapter=typeAdapter
        //商品
        viewModel.indexGoods(type,limit,page)
        goodsAdapter= GoodsAdapter()
        binding.rvGoods.layoutManager=GridLayoutManager(requireContext(),2)
        binding.rvGoods.adapter=goodsAdapter
        //上划加载  下拉刷新
        binding.sm.setOnRefreshLoadMoreListener(object :OnRefreshLoadMoreListener{
            override fun onRefresh(refreshLayout: RefreshLayout) {
                page=1
                viewModel.indexGoods(type,limit,page)
                binding.sm.finishRefresh()
            }

            override fun onLoadMore(refreshLayout: RefreshLayout) {
                viewModel.indexGoods(type,limit,++page)
                binding.sm.finishLoadMore()
            }

        })
        //点击分类  下方商品数据可以变化
        typeAdapter.setOnItemClickListener { adapter, view, position ->
            type=typeAdapter.data[position].type.toInt()
            page=1
            viewModel.indexGoods(type,limit,page)
            typeAdapter.setType(type)
        }
        //优惠券
        viewModel.coupon("10","1","1")
        couponAdapter=CouponAdapter()
        binding.rvCoupon.layoutManager=LinearLayoutManager(requireContext(),LinearLayoutManager.HORIZONTAL,false)
        binding.rvCoupon.adapter=couponAdapter
        //点击优惠券领取
        couponAdapter.setOnItemClickListener { adapter, view, position ->
            couponIndex=position
            if(couponAdapter.data[position].isUse){
                ToastUtils.showLong("不能重复领取")
            }else{
                viewModel.couponReceive(couponAdapter.data[position].id)
            }
        }
    }

    override fun initData() {
        //观察数据
        viewModel.indexSuccess.observe(this){
            if(it.code==200){
                //轮播图
                it.data.banner.forEach {
                    imgs.add(it.pic)
                }
                binding.banner.setImages(imgs)
                    .setImageLoader(object :ImageLoader(){
                        override fun displayImage(
                            context: Context?,
                            path: Any?,
                            imageView: ImageView?
                        ) {
                            if(context!=null&&path!=null&&imageView!=null){
                                GlideUtils.loadImage(context,path.toString(),imageView)
                            }
                        }
                    })
                    .setDelayTime(2000)//轮播时长
                    .setBannerStyle(BannerConfig.NUM_INDICATOR)
                    .setOnBannerListener {
                        ToastUtils.showLong("点击的是第${it}张图片")
                    }
                    .start()
                //显示菜单
                menuAdapter.data.clear()
                menuAdapter.data.addAll(it.data.menus)
                menuAdapter.notifyDataSetChanged()
                //新闻
                newsAdapter.data.clear()
                newsAdapter.data.addAll(it.data.roll)
                newsAdapter.data.add(Roll(1,"双11预售","",""))
                newsAdapter.notifyDataSetChanged()
                //分类
                typeAdapter.data.clear()
                typeAdapter.data.addAll(it.data.explosiveMoney)
                typeAdapter.notifyDataSetChanged()
            }else{
                ToastUtils.showLong(it.message)
            }
        }
        //商品
        viewModel.goodsSuccess.observe(this){
            if(it.code==200){
                if(page==1){
                    goodsAdapter.data.clear()
                }
                goodsAdapter.data.addAll(it.data.list)
                goodsAdapter.notifyDataSetChanged()
                //当请求不出新的数据时  可以给出友好提示
                if(it.data.list.size==0){
                    ToastUtils.showLong("我也是有底线的~")
                }
            }else{
                ToastUtils.showLong(it.message)
            }
        }
        //优惠券
        viewModel.couponSuccess.observe(this){
            if(it.code==200){
                couponAdapter.data.clear()
                couponAdapter.data.addAll(it.data)
                couponAdapter.notifyDataSetChanged()
            }else{
                ToastUtils.showLong(it.message)
            }
        }
        //领取优惠券
        viewModel.couponReceiveSuccess.observe(this){
            if(it.code==200){
                couponAdapter.data[couponIndex].isUse=true
                couponAdapter.notifyDataSetChanged()
            }
            ToastUtils.showLong(it.message)
        }
    }

    override fun getViewModel(): Class<HomeVieModel> {
        return HomeVieModel::class.java
    }

    override fun getLayoutId(): Int {
       return R.layout.fragment_home
    }

}